package cn.hackcloud.javabase.thread;

class Clerk {
	int prodcut;

	// 生产产品
	public synchronized void addProduct() throws Exception {
		if (prodcut >= 20) {
			wait();
		} else {
			prodcut++;
			System.err.println(Thread.currentThread().getName() + ":生产了第" + prodcut + "个产品！");
			notifyAll();
		}
	}

	// 消费产品
	public synchronized void consumeProduct() throws Exception {
		if (prodcut <= 0) {
			wait();
		} else {
			System.err.println(Thread.currentThread().getName() + ":消费了第" + prodcut + "个产品！");
			prodcut--;
			notifyAll();
		}

	}
}

class Producer implements Runnable {
	Clerk clerk;

	public Producer(Clerk clerk) {
		this.clerk = clerk;
	}

	@Override
	public void run() {
		System.err.println("生产者开始生产产品！");
		while (true) {
			try {
				Thread.sleep(100);
				clerk.addProduct();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

}

class Consumer implements Runnable {
	Clerk clerk;

	public Consumer(Clerk clerk) {
		this.clerk = clerk;
	}

	@Override
	public void run() {
		System.err.println("消费者开始消费产品！");
		while (true) {
			try {
				clerk.consumeProduct();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}

public class TestProduceConsume {
	public static void main(String[] args) {
		Clerk clerk = new Clerk();
		Producer producer = new Producer(clerk);
		Consumer consumer = new Consumer(clerk);
		Thread t1 = new Thread(producer);
		Thread t2 = new Thread(consumer);
		Thread t3 = new Thread(producer);
		t1.start();
		t2.start();
		t3.start();
	}
}
